# -*- coding:utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtSql import (QSqlDatabase, QSqlQuery, QSqlTableModel)
import sys
import re
import os
reload(sys)
sys.setdefaultencoding('utf-8')
import time,math
from lib.pyhk import *
import locale
import sqlite3

class MyThread(QThread):
    sec_changed_signal = pyqtSignal(int)  # 信号类型：int

    def __init__(self, sec=1000, parent=None):
        QThread.__init__(self, parent)
        # super().__init__(parent)
        self.sec = sec  # 默认1000秒

    def run(self):
        for i in range(self.sec):
            # time.sleep(1)
            print('run1')
            self.sec_changed_signal.emit(i)  # 发射信号
            time.sleep(6) #0 * 60
            print('run')


class Worker2(QThread):
    def __init__(self, parent=None):
        QThread.__init__(self, parent)

    def get_mem_error_logfile_content(self):
        print(1212)

    def get_mem_right_logfile_content(self):
        print '*' * 30


def run(self):
    self.emit(SIGNAL("get_log_start()"))  # 触发定时器信号

class runtable(QWidget):
    close_signal = pyqtSignal()
    def __init__(self, parent=None):
        super(runtable, self).__init__(parent)
        self.cx = sqlite3.connect("reference.db", check_same_thread=False)
        self.myquery = self.cx.cursor()
        self.count = 0
        print(1212)

        self.removelist = []
        self.run_day = time.localtime().tm_yday
        self.now_day = time.localtime().tm_yday
        self.m30_7once = True
        # 按钮布局
        layout = QVBoxLayout()
        self.pbLogin = QPushButton(u'登录', self)
        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.pbLogin)
        layout.addLayout(buttonLayout)

        self.setLayout(layout)
        self.setWindowOpacity(0)
        print('main')
        try:
            thread = MyThread()  # 创建一个线程
            thread.sec_changed_signal.connect(self.update)  # 线程发过来的信号挂接到槽：update
            self.pbLogin.clicked.connect(lambda: thread.start())
            thread.start()

        except ZeroDivisionError as err:  # as 加原因参数名称
            print('Exception: ', err)



    def update1(self):
        print(1211111)
        self.update(1)

    def __del__(self):
        self.cx.close()

        # try:
        #     thread = MyThread()  # 创建一个线程
        #     thread.sec_changed_signal.connect(self.update)  # 线程发过来的信号挂接到槽：update
        #     # self.pbLogin.clicked.connect(lambda: thread.start())
        #     thread.start()
        #
        # except ZeroDivisionError as err:  # as 加原因参数名称
        #     #print('Exception: ', err)

    def update(self):
        # time.sleep(i)
        # QMessageBox.about(self, '提醒', "密码输入错误，请重试")
        self.now_day = time.localtime().tm_yday
        if self.run_day != self.now_day:
            self.m30_7once = True
        print("update")
        self.process()

        # self.btn = QToolButton(self)
        # self.btn
        # .setText("click")

    def process(self):
        #threading.Thread(target=self.threadRun).start()
        select_date = self.myquery.execute('SELECT * FROM reference').fetchall()
        #print(select_date)
        res = select_date
        # print res
        try:
            for line in res:
                # print line[0]
                #print(u"提醒前查询"+str(line[0]) + line[1] + line[2])
                self.showWarn(line[1], line[2], line[3],str(line[0]),line[4])
        # except ZeroDivisionError as err:  # as 加原因参数名称
            #print('Exception: ', err)
        finally:
            self.m30_7once = False
            # for rminfo in self.removelist:
            #     self.removeWarn(rminfo["vid"], rminfo["value"])
            str1 = 'QWidget{font-size:12px;}'
            # self.setStyleSheet(str1)
            # time.sleep(10)
            # self.update(1)
            # print(self.m30_7once)
            self.count = self.count+1
            print(self.count)
            # if self.count<3:
            #     self.threading.Thread(target=self.update)

    def process1(self):
        time.sleep(3)
        self.process()
    def removeWarn(self,vid,value):

        #print(vid+u" 验证码为:"+value)
        try:
            sql = '''select count(*) from sjm where sjmm='?' '''
            #print(sql)
            myres = self.myquery.execute(sql).fetchone()
            #print(myres)
            if myres[0]:
                num = myres[0]
                #print(myres[0])
                if num == 1:
                    #print(u'正确的随机码')
                    vsql = "delete  from reference where id='" + vid + "'"
                    #print(vsql)
                    self.myquery.execute(vsql)

                    vsql = "delete  from sjm where sjmm='" + value + "'"
                    #print(vsql)
                    self.myquery.execute(vsql)

                # return True
            # else:
                #print('错误的随机码')
                # return True
        # except ZeroDivisionError as err:  # as 加原因参数名称
            #print('Exception: ', err)
        finally:
            self.cx.commit()


    def showWarn(self,vtime,vdesc,vyzm,vid,vfontsize):
        # try:
        category = vtime
        #print(category)
        waring_t = time.strptime(category, "%Y-%m-%d")
        #print(waring_t)
        waring_time = time.mktime(waring_t)
        #print(waring_time)
        now = time.localtime(time.time())
        nowtime = time.time()
        #print(now)
        #print(nowtime)
        str1 = 'QWidget{font-size:' + str(vfontsize) + 'px;}'
        #print(str1)

        left = math.floor((waring_time - nowtime)/(24*60*60))
        #print("left"+str(left))
        if left<0:
            left = 0

        desc = vdesc
        desc = desc.replace('{left}', '<span style=color:red; size=50px >' + str(int(left)) + '</span>')
        warning = u"提醒时间：" + category + u";提醒内容:" + desc;
        #print(u"验证码为："+vyzm)
        if left < 30:
            if left > 7 and self.m30_7once:
                if vyzm == u'是':
                    #print('进入大于七天')
                    infoBox = InputDialog(desc,vfontsize,1,vid,left)
                    # self.setStyleSheet(str1)
                    # self.setWindowFlags(Qt.WindowMinimizeButtonHint| Qt.WindowStaysOnTopHint)
                    infoBox.show()
                    # value = infoBox.selectName()
                    # #print(value)
                    # self.removeWarnbefore(vid, value)
                else:
                    infoBox = InputDialog(desc, vfontsize, 0,vid,left)
                    infoBox.show()
            if left <= 7:
                if vyzm == u'是':
                    #print('进入大于七天')
                    infoBox = InputDialog(desc,vfontsize,1,vid,left)
                    # self.setStyleSheet(str1)
                    # self.setWindowFlags(Qt.WindowMinimizeButtonHint| Qt.WindowStaysOnTopHint)
                    infoBox.show()
                    # value = infoBox.selectName()
                    # #print(value)
                    # self.removeWarnbefore(vid, value)
                else:
                    infoBox = InputDialog(desc, vfontsize, 0,vid,left)
                    infoBox.show()
        # except Exception as e:
            #print(e)
            #print('download exception %s' % str1)

    def removeWarnbefore(self,vid, value):
        sdict = {}
        sdict['vid']=vid
        sdict['value']=value
        self.removelist.append(sdict)
        #print(self.removelist)


class InputDialog(QWidget):
    def __init__(self,txnr,ztdx,dtype,vid,left):
        super(InputDialog, self).__init__()
        self.setWindowFlags(Qt.Tool | Qt.WindowMinimizeButtonHint| Qt.WindowStaysOnTopHint | Qt.X11BypassWindowManagerHint| Qt.FramelessWindowHint )#
        self.txnr = txnr
        self.ztdx = ztdx
        self.dtype = dtype
        self.vid = vid
        self.left = left
        # self.setAcceptDrops(True)
        self.initUi()
        # 创建hotkey句柄
        hot_handle = pyhk()
        hot_handle.addHotkey(['Ctrl', 'T'], self.hkfunc)
        hot_handle.addHotkey(['Ctrl', 'B'], self.close)
        self.cx = sqlite3.connect("reference.db")
        self.myquery = self.cx.cursor()
        if self.left!=0 or self.dtype!=1:
            self.createContextMenu()

    def showContextMenu(self, pos):
        '''''
        右键点击时调用的函数
        '''
        # 菜单显示前，将它移动到鼠标点击的位置
        self.contextMenu.move(self.pos() + pos)
        self.contextMenu.show()

    def createContextMenu(self):
        '''''
        创建右键菜单
        '''
        # 必须将ContextMenuPolicy设置为Qt.CustomContextMenu
        # 否则无法使用customContextMenuRequested信号
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showContextMenu)

        # 创建QMenu
        self.contextMenu = QMenu(self)
        self.actionA = self.contextMenu.addAction(u'关闭')
        #self.actionB = self.contextMenu.addAction(u'动作B')
        #self.actionC = self.contextMenu.addAction(u'动作C')
        # 将动作与处理函数相关联
        # 这里为了简单，将所有action与同一个处理函数相关联，
        # 当然也可以将他们分别与不同函数关联，实现不同的功能
        self.actionA.triggered.connect(self.close)
        #self.actionB.triggered.connect(self.actionHandler)
        #self.actionB.triggered.connect(self.actionHandler)

    def hkfunc(self):
        # print 'afe'
        import subprocess
        # subprocess.call(r"D:\do\Python\py_gui\v1\dist\WDMSET-v1.exe")
        subprocess.Popen(r"WDMSET-v1.exe", shell=False, close_fds=True)

    # def mousePressEvent(self, event):
    #     # print QEvent.FocusOut, 'mousePressEvent', event.type()
    #     if event.button() == Qt.LeftButton:
    #         self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
    #         QApplication.postEvent(self, QEvent(174))
    #         event.accept()
    #
    # def mouseMoveEvent(self, event):
    #     if event.buttons() == Qt.LeftButton:
    #         self.move(event.globalPos() - self.dragPosition)
    #         event.accept()

    def initUi(self):
        self.setWindowTitle(u"提醒")
        # self.setGeometry(100, 100, 200, 200)


        label1 = QLabel(self.txnr)
        # label1.adjustSize()
        # label1.width = 200
        # label1.setGeometry(QRect(328, 240, 329, 27*4))
        # label1.setWordWrap(True)
        # label1.setAlignment(Qt.AlignTop)
        label1.setAlignment(Qt.AlignCenter)
        label1.setFont(QFont("Roman times", self.ztdx))

        self.nameLable = QLineEdit(u"请输入激活码，关闭获延期本弹窗")
        # self.nameLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.styleLable = QLabel("外包")
        self.styleLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.numberLable = QLabel("40")
        self.numberLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.costLable = QLabel("400.98")
        self.costLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.introductionLable = QLabel("服务外包第三方公司")
        self.introductionLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)

        nameButton = QPushButton(u"清除任务")
        nameButton.clicked.connect(self.selectName)
        styleButton = QPushButton("...")
        styleButton.clicked.connect(self.selectStyle)
        numberButton = QPushButton("...")
        numberButton.clicked.connect(self.selectNumber)
        costButton = QPushButton("...")
        costButton.clicked.connect(self.selectCost)
        introductionButton = QPushButton("...")
        introductionButton.clicked.connect(self.selectIntroduction)

        mainLayout = QGridLayout()
        mainLayout.addWidget(label1, 0, 0)
        if self.dtype == 1:
            mainLayout.addWidget(self.nameLable, 1, 0)
            mainLayout.addWidget(nameButton, 2, 0)

        self.setLayout(mainLayout)
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        #print(size)
        self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)

    def selectName(self):
        inputext =  self.nameLable.text()
        #print("inputext"+inputext)
        try:
            sql = "select count(*) from sjm where sjmm='" + str(inputext) + "'"
            #print(sql)

            select_date = self.myquery.execute(sql).fetchone()
            #print(select_date)
            if select_date[0]==1:
                #print('正确的随机码')
                vsql = "delete  from reference where id='" + str(self.vid) + "'"
                #print(vsql)
                self.myquery.execute(vsql)

                vsql = "delete  from sjm where sjmm='" + str(inputext) + "'"
                #print(vsql)
                self.myquery.execute(vsql)
                #关闭本窗口
                self.hide()
            # else:
                #print('错误的随机码')
                # return True
        # except ZeroDivisionError as err:  # as 加原因参数名称
            #print('Exception: ', err)
        finally:
            self.cx.commit()
    #print('afeiafei')

    def selectStyle(self):
        list = ["外包", "自研"]

        style, ok = QInputDialog.getItem(self, "项目性质", "请选择项目性质：", list)
        if ok:
            self.styleLable.setText(style)

    def selectNumber(self):
        number, ok = QInputDialog.getInt(self, "项目成员", "请输入项目成员人数：", int(self.numberLable.text()), 20, 100, 2)
        if ok:
            self.numberLable.setText(str(number))

    def selectCost(self):
        cost, ok = QInputDialog.getDouble(self, "项目成本", "请输入项目成员人数：", float(self.costLable.text()), 100.00, 500.00, 2)
        if ok:
            self.costLable.setText(str(cost))

    def selectIntroduction(self):
        introduction, ok = QInputDialog.getMultiLineText(self, "项目介绍", "介绍：", "服务外包第三方公司 \nPython project")
        if ok:
            self.introductionLable.setText(introduction)


def run(i):
    mywin = runtable()
    mywin.show()
    mywin.update()

import threading
app = QApplication(sys.argv)

i=0
# while i<12:
#     i+=1
#     print "start", time.strftime("%Y-%m-%d_%H-%M-%S")
#     t = threading.Thread(target=run, args=(0,))
#     t.run()
#     print "end", time.strftime("%Y-%m-%d_%H-%M-%S")
run(1)
sys.exit(app.exec_())
# run()

import threading
# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     # window = InputDialog(u'您好，该维修了您好，该维修了您好，该维修了您好，该维修了您好，该维修了您好，该维修了您好，该维修了',15,1)
#     # window.show()
#
#     # i=0
#     # while i < 10:
#     #     mywin = runtable()
#     #     thread1 = threading.Thread(target=mywin.update1)
#     #     thread1.start()
#     #     time.sleep(5)
#     #     i = i + 1
#     mywin = runtable()
#     mywin.update(1)
#     sys.exit(app.exec_())